<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="比价单号" prop="orderCode">
        <el-input
          v-model="queryParams.orderCode"
          placeholder="请输入比价单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="询价单号" prop="inquireCode">
        <el-input
          v-model="queryParams.inquireCode"
          placeholder="请输入询价单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="厂家" prop="manufacturerId">
        <el-select v-model="queryParams.manufacturerId" placeholder="请选择厂家">
          <el-option
            v-for="item in entOptions"
            :key="item.id"
            :label="item.entName"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态">
          <el-option
            v-for="dict in dict.type.wms_price_comparison_order_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['wms:priceComparisonOrder:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['wms:priceComparisonOrder:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['wms:priceComparisonOrder:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['wms:priceComparisonOrder:add']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-setting"
          size="mini"
          @click="handleContrast"
          v-hasPermi="['wms:priceComparisonOrder:contrast']"
        >比价</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="priceComparisonOrderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" :selectable="handelIsSelect"/>
      <el-table-column label="比价单号" align="center" prop="orderCode" >
        <template slot-scope="scope">
          <el-link type="primary" @click="handleLook(scope.row)">{{ scope.row.orderCode }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="询价单号" align="center" prop="inquireCode" />
      <el-table-column label="询价有效期" align="center" prop="inquireValid" />
      <el-table-column label="厂家" align="center" prop="manufacturerName" />
      <el-table-column label="交货期" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.jhValid && scope.row.jhValid != 'null'">{{scope.row.jhValid}}天</span>
          <span v-else>无</span>
        </template>
      </el-table-column>
      <el-table-column label="总价" align="center" prop="allPrice" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.wms_price_comparison_order_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="比价" align="center" prop="isBj">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.isBj"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-if="scope.row.status === '0'"
            v-hasPermi="['wms:priceComparisonOrder:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-if="scope.row.status === '0'"
            v-hasPermi="['wms:priceComparisonOrder:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改比价单管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="90%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="询价单" prop="inquireCode">
              <el-select v-model="form.inquireCode" :disabled="form.orderCode != null && form.orderCode != ''" filterable @change="handelInquireCodeChange" placeholder="请选择询价单编码" clearable>
                <el-option
                  v-for="dict in inquireOrderOptions"
                  :key="dict.orderCode"
                  :label="dict.orderCode"
                  :value="dict.orderCode"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="厂家" prop="manufacturerId">
              <el-select v-model="form.manufacturerId" @change="handleManufactureChange" clearable placeholder="请选择厂家">
                <el-option
                  v-for="item in entOptions"
                  :key="item.id"
                  :label="item.entName"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="总价" prop="allPrice">
              <el-input v-model="form.allPrice" placeholder="请输入商品总价"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="交货期" prop="jhValid">
              <el-input placeholder="请输入交货期" v-model="form.jhValid">
                <template slot="append">天</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12" v-if="!form.orderCode">
            <el-form-item>
              <template slot="label">
                是否比价
                <el-tooltip class="item" effect="dark" content="如果选择无需比价，则直接会进入比价单审核" placement="bottom">
                  <i class="el-icon-warning-outline"></i>
                </el-tooltip>
              </template>
              <el-radio-group v-model="form.isBj">
                <el-radio
                  v-for="dict in dict.type.sys_yes_no"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="附件" prop="accessoryList">
          <el-upload
            class="upload-demo"
            :headers="upload.headers"
            :action="upload.urlImage"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            multiple
            accept=".jpg,.png,.jpeg"
            :file-list="fileList"
            drag
            style="width: 100%">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip text-center" slot="tip">
              <span>仅允许导入jpg/png/pdf格式文件。</span>
            </div>
          </el-upload>
        </el-form-item>
        <h1>订单商品</h1>
        <el-table :data="products">
          <el-table-column label="序号" align="center" type="index" width="50"/>
          <el-table-column label="商品编码" align="center" prop="productCode" :show-overflow-tooltip="true"/>
          <el-table-column label="商品名称" align="center" prop="productName" :show-overflow-tooltip="true"/>
          <el-table-column label="商品类型" align="center" prop="productTypeName"/>
          <el-table-column label="计数单位" align="center" prop="unitName"/>
          <el-table-column label="商品数量" align="center" prop="productNum"/>
          <el-table-column label="指定厂家" align="center" prop="purchaseCompanyName"/>
          <el-table-column label="单价" align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.onlyPrice" @blur="handleOnlyPrice(scope.row)" placeholder="请输入商品单价"/>
            </template>
          </el-table-column>
          <el-table-column label="总价" align="center" prop="allPrice">
            <template slot-scope="scope">
              <el-input v-model="scope.row.allPrice" @blur="handleAllPrice(scope.row)" placeholder="请输入商品总价"/>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDeleteProduct(scope.$index)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-loading="btnLoading" v-if="form.orderCode && form.isBj === 'N'">审 核</el-button>
        <el-button type="primary" @click="submitForm" v-loading="btnLoading" v-else>确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 比价单商品对话框 -->
    <el-dialog title="比价单详情" :visible.sync="openLook" width="80%" append-to-body>
      <el-form>
        <el-form-item label="比价单号" >
          {{orderCode}}
        </el-form-item>

        <el-form-item label="附件">
          <el-upload
            action=""
            class="upload-demo"
            :disabled="true"
            :on-preview="handlePreview"
            :file-list="fileList">
          </el-upload>
        </el-form-item>
      </el-form>
      <h1>商品信息</h1>
      <el-table :data="orderProductTable">
        <el-table-column label="序号" align="center" type="index" width="50"/>
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-form label-position="left" inline class="demo-table-expand">
              <el-row :gutter="10">
                <el-col :span="12">
                  <el-form-item label="商品编码">
                    <span>{{ props.row.productCode }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="商品类型">
                    <span>{{ props.row.productTypeName }}</span>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="10">
                <el-col :span="12">
                  <el-form-item label="计数单位">
                    <span>{{ props.row.unitName }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="尺寸单位">
                    <span>{{ props.row.ccUnitName }}</span>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="10">
                <el-col :span="12">
                  <el-form-item label="尺寸">
                    <span v-if="props.row.longWith || props.row.weight || props.row.height">{{ props.row.longWith + '*' + props.row.weight + '*' + props.row.height }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="重量">
                    <span>{{ props.row.zl }}</span>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-form-item label="详情">
                <span>{{ props.row.detail }}</span>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column label="商品名称" align="center" prop="productName" :show-overflow-tooltip="true"/>
        <el-table-column label="商品型号" align="center" prop="modal" :show-overflow-tooltip="true"/>
        <el-table-column label="商品数量" align="center" prop="productNum"/>
        <el-table-column label="生产厂家" align="center" prop="scPurchaseCompanyName"/>
        <el-table-column label="单价" align="center" prop="onlyPrice"/>
        <el-table-column label="总价" align="center" prop="allPrice"/>
      </el-table>
    </el-dialog>

    <!-- 比价单导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="600px" append-to-body>
      <el-form ref="formImport" :model="upload.form" :rules="upload.rules" label-width="100px">
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="厂家" prop="manufacturerId">
              <el-select v-model="upload.form.manufacturerId" filterable  @change="handleManufactureChange" clearable placeholder="请选择厂家">
                <el-option
                  v-for="item in entOptions"
                  :key="item.id"
                  :label="item.entName"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="交货期" prop="jhValid">
              <el-input placeholder="请输入交货期" v-model="upload.form.jhValid">
                <template slot="append">天</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item>
              <template slot="label">
                是否比价
                <el-tooltip class="item" effect="dark" content="如果选择无需比价，则直接会进入比价单审核" placement="bottom">
                  <i class="el-icon-warning-outline"></i>
                </el-tooltip>
              </template>
              <el-radio-group v-model="upload.form.isBj">
                <el-radio
                  v-for="dict in dict.type.sys_yes_no"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="附件" prop="manufacturerId">
          <el-upload
            ref="upload"
            :limit="1"
            accept=".jpg,.png,.jpeg"
            :headers="upload.headers"
            :action="upload.urlImage"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            :file-list="fileList"
            drag
            multiple
            style="width: 100%"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip text-center" slot="tip">
              <span>仅允许导入jpg/png/pdf格式文件。</span>
            </div>
          </el-upload>
        </el-form-item>
      </el-form>

      <el-divider content-position="left">询价单导入</el-divider>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?manufacturerName=' + upload.form.manufacturerName + '&manufacturerId=' + upload.form.manufacturerId
         + '&jhValid=' + upload.form.jhValid + '&accessoryList=' + accessoryList + '&isBj=' + upload.form.isBj"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
        style="width: 100%"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="cancelImport">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 比价单比价对话框 -->
    <el-dialog :title="title" :visible.sync="openContrast" width="500px" append-to-body>
      <p style="color: red">注：只有高于等于3家厂家报价的询价单才会展示在此</p>
      <el-form ref="formContrast" :model="formContrast" :rules="rulesContrast" label-width="80px">
        <el-form-item label="询价单" prop="inquireCode">
          <el-select v-model="formContrast.inquireCode" filterable placeholder="请选择询价单编码" clearable>
            <el-option
              v-for="dict in inquireOrderContrastOptions"
              :key="dict"
              :label="dict"
              :value="dict"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormContrast" v-loading="btnLoading">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 比价单比价对话框 -->
    <el-dialog title="比价单比价" custom-class="bjDetail" :visible.sync="openContrastDetail" fullscreen append-to-body>
      <comparison-product ref="comparisonProduct" :open-flag="openContrastDetail" :contrast-product-table="contrastProductTable"/>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormContrastDetail" v-loading="btnLoading">确 定</el-button>
        <el-button @click="openContrastDetail = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listPriceComparisonOrder,
  getPriceComparisonOrder,
  delPriceComparisonOrder,
  addPriceComparisonOrder,
  updatePriceComparisonOrder,
  getPriceComparisonInquire,
  getContrastInquireOrder, contrastPriceComparisonOrder
} from "@/api/wms/priceComparisonOrder";
import {listEntXlk} from "@/api/wms/ent";
import {
  getInquireOrder,
  getOrderProduct,
  listInquireOrderXlk
} from "@/api/wms/inquireOrder";
import {getToken} from "@/utils/auth";
// import comparisonProduct from "@/views/wms/priceComparisonOrder/components/comparisonProduct-bat.vue";
import comparisonProduct from "@/views/wms/priceComparisonOrder/components/comparisonProduct.vue";

export default {
  name: "PriceComparisonOrder",
  dicts: ['wms_price_comparison_order_status', 'sys_yes_no'],
  components: {comparisonProduct},
  data() {
    return {
      pickerOptions: {
        disabledDate(time) {
          //时间选择框必须大于今天
          return time.getTime() < Date.now() - 8.64e7;
          // 或者 return time.getTime() < Date.now();
        }
      },
      prefix: process.env.VUE_APP_BASE_API,
      orderCode: null,
      //按钮加载
      btnLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 比价单管理表格数据
      priceComparisonOrderList: [],
      // 供应商集合
      entOptions: [],
      // 询价单集合
      inquireOrderOptions: [],
      // 询价单比价集合
      inquireOrderContrastOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 详情显示弹出层
      openLook: false,
      // 比价显示弹出层
      openContrast: false,
      // 比价详情显示弹出层
      openContrastDetail: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        manufacturerId: null,
        inquireCode: null,
        status: null,
        orderCode: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        inquireCode:[
          { required: true, message: "询价单不能为空", trigger: "blur" }
        ],
        manufacturerId:[
          { required: true, message: "请选择厂家", trigger: "blur" }
        ],
        allPrice:[
          { required: true, message: "商品总价不能为空", trigger: "blur" },
          { pattern: /^(0|[1-9])\d{0,6}(\.\d{1,2})?$/, message: '商品总价只能是数值最大7位整数2位小数', trigger: 'blur' }
        ],
        jhValid: [
          // { required: true, message: "请输入交货期", trigger: "blur" },
          { pattern: /^(0|[1-9])\d{0,4}$/, message: '交货期只能是数值最多5位数', trigger: 'blur' }
        ],
        accessoryList: [
          { required: true, message: "请上传附件", trigger: "blur" }
        ]
      },
      // 证明集合
      fileList: [],
      // 询价单导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/wms/priceComparisonOrder/importData",
        urlImage: process.env.VUE_APP_BASE_API + "/wms/priceComparisonOrder/uploadPic",
        form: {
          manufacturerId: null,
          manufacturerName: null,
          jhValid: null,
          accessoryList: null,
          isBj: 'Y'
        },
        rules:{
          manufacturerId: [
            { required: true, message: "请选择厂家", trigger: "blur" }
          ],
          jhValid: [
            // { required: true, message: "请输入交货期", trigger: "blur" },
            { pattern: /^(0|[1-9])\d{0,4}$/, message: '交货期只能是数值最多5位数', trigger: 'blur' }
          ],
          accessoryList: [
            { required: true, message: "请上传附件", trigger: "blur" }
          ]
        }
      },
      // 附件列表
      accessoryList: [],
      // 商品详情
      products: [],
      // 比价单商品详情
      orderProductTable: [],
      formContrast:{
        inquireCode: null
      },
      rulesContrast:{
        inquireCode: [
          { required: true, message: "请选择询价单", trigger: "blur" }
        ]
      },
      //比价单商品列表
      contrastProductTable: []
    };
  },
  created() {
    this.getList();
    this.getEntList();
    this.getInquireXlk();
  },
  methods: {
    /** 查询比价单管理列表 */
    getList() {
      this.loading = true;
      listPriceComparisonOrder(this.queryParams).then(response => {
        this.priceComparisonOrderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询供应商列表 */
    getEntList() {
      listEntXlk({entType: '1', gysType: '1'}).then(response => {
        this.entOptions = response.data;
      });
    },
    /** 查询询价单下拉框 */
    getInquireXlk() {
      listInquireOrderXlk().then(response => {
        this.inquireOrderOptions = response.data;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.openContrast = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.accessoryList = []
      this.products = []
      this.fileList = []
      this.formContrast.inquireCode = null
      this.form = {
        orderCode: null,
        manufacturerId: null,
        manufacturerName: null,
        inquireCode: null,
        allPrice: 0,
        accessoryId: null,
        accessoryList: null,
        jhValid: null,
        isBj: 'Y'
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.orderCode)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加比价单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const orderCode = row.orderCode || this.ids
      getPriceComparisonOrder(orderCode).then(response => {
        this.form = response.data;
        this.products = this.form.products
        this.accessoryList = this.form.accessoryList
        if (this.accessoryList && this.accessoryList.length > 0) {
          this.accessoryList.forEach(item => {
            let urls = item.split("/")
            this.fileList.push({name: urls[urls.length - 1], url: this.prefix + item})
          })
        } else {
          this.accessoryList = []
        }
        this.open = true;
        this.title = "修改比价单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          let msg = ''
          if (this.products.length > 0) {
            let reg = /^(0|[1-9])\d{0,6}(\.\d{0,2})?$/
            for (let i = 0; i < this.products.length; i++) {
              let item = this.products[i];
              if (item.onlyPrice) {
                if (!reg.test(item.onlyPrice)) {
                  msg += "第" + (i+1) +"行格式异常，商品单价只能是数值最大7位整数2位小数；"
                }
              } else {
                msg += "第" + (i+1) +"行格式异常，商品单价不能为空；"
              }
              if (item.allPrice) {
                if (!reg.test(item.allPrice)) {
                  msg += "第" + (i+1) +"行格式异常，商品总价只能是数值最大7位整数2位小数；"
                }
              } else {
                msg += "第" + (i+1) +"行格式异常，商品总价不能为空；"
              }
              if (item.purchaseCompany && this.form.manufacturerId !== item.purchaseCompany) {
                msg += "第" + (i+1) +"行格式异常，选择厂家与商品指定厂家不符；"
              }
            }

            if (msg) {
              this.$message.error(msg)
            } else {
              this.btnLoading = true
              this.form.products = this.products
              this.form.accessoryList = this.accessoryList
              if (this.form.orderCode != null) {
                updatePriceComparisonOrder(this.form).then(response => {
                  if (response.code == 200) {
                    this.$modal.msgSuccess("修改成功");
                    this.open = false;
                    this.getList();
                  } else {
                    this.$modal.msgError(response.msg);
                  }
                }).finally(f => {
                  this.btnLoading = false
                });
              } else {
                addPriceComparisonOrder(this.form).then(response => {
                  if (response.code == 200) {
                    this.$modal.msgSuccess("新增成功");
                    this.open = false;
                    this.getList();
                  } else {
                    this.$modal.msgError(response.msg);
                  }
                }).finally(f => {
                  this.btnLoading = false
                });
              }
            }
          } else {
            this.$message.error("商品信息不可为空！")
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const orderCodes = row.orderCode || this.ids;
      this.$modal.confirm('是否确认删除比价单管理编号为"' + orderCodes + '"的数据项？').then(function() {
        return delPriceComparisonOrder(orderCodes);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    // 是否可以选择
    handelIsSelect(row, index){
      return row.status === '0'
    },
    // 厂家变更事件
    handleManufactureChange(val) {
      if (val){
        let ent = this.entOptions.filter(item => item.id === val)
        this.form.manufacturerName = ent[0].entName
        this.upload.form.manufacturerName = ent[0].entName
      } else {
        this.form.manufacturerName = null
        this.upload.form.manufacturerName = null
      }
    },
    // 询价单变更事件
    handelInquireCodeChange(val) {
      this.products = []
      if (val){
        getInquireOrder(val).then(async response => {
          this.products = response.data.products
        });
      }
    },
    //单价失去焦点事件
    handleOnlyPrice(row){
      if (row.onlyPrice) {
        let reg = /^(0|[1-9])\d{0,6}(\.\d{0,2})?$/
        if (!reg.test(row.onlyPrice)) {
          this.$notify.error("商品单价只能是数值，最大7位整数2位小数")
        } else {
          row.allPrice = (row.productNum * row.onlyPrice).toFixed(2)

          let allPrice = this.form.allPrice
          if (allPrice === null || allPrice === undefined) {
            allPrice = 0
          }
          if (row.oldAllPrice != null && row.oldAllPrice != undefined) {
            allPrice -= row.oldAllPrice
          }
          row.oldAllPrice = row.allPrice

          this.form.allPrice = (parseFloat(allPrice) + parseFloat(row.allPrice)).toFixed(2)
        }
      } else {
        let fAllPrice = this.form.allPrice
        let allPrice = row.allPrice
        if (fAllPrice !== null && fAllPrice !== undefined) {
          if (allPrice !==null && allPrice !== undefined) {
            this.form.allPrice = (parseFloat(fAllPrice) - parseFloat(allPrice)).toFixed(2)
          }
        }
        if (allPrice !== null && allPrice !== undefined) {
          row.allPrice = null
          row.oldAllPrice = null
        }
      }
    },
    //总价失去焦点事件
    handleAllPrice(row){
      if (row.allPrice !== null && row.allPrice !== undefined) {
        let reg = /^(0|[1-9])\d{0,6}(\.\d{0,2})?$/
        if (!reg.test(row.allPrice)) {
          this.$notify.error("商品总价只能是数值，最大7位整数2位小数")
        } else {
          let allPrice = this.form.allPrice
          if (allPrice === null || allPrice === undefined) {
            allPrice = 0
          }
          if (row.oldAllPrice !== null && row.oldAllPrice !== undefined) {
            allPrice = parseFloat(allPrice) - parseFloat(row.oldAllPrice)
          }
          this.form.allPrice = (parseFloat(allPrice) + parseFloat(row.allPrice)).toFixed(2)
          row.oldAllPrice = row.allPrice
        }
      } else {
        let allPrice = this.form.allPrice
        if (allPrice !== null && allPrice !== undefined) {
          if (row.oldAllPrice !== null && row.oldAllPrice !== undefined) {
            allPrice = parseFloat(allPrice) - parseFloat(row.oldAllPrice)
          }
          this.form.allPrice = parseFloat(allPrice).toFixed(2)
        }
        row.oldAllPrice = null
      }
    },
    // 删除比价单商品
    handleDeleteProduct(index){
      this.products.splice(index, 1);
    },
    handleRemove(file, fileList) {
      this.accessoryList.splice(this.accessoryList.indexOf(file.url), 1);
      if (this.accessoryList.length === 0) {
        this.form.accessoryList = null
        this.upload.form.accessoryList = null
      }
    },
    // 附件上传成功处理
    handleSuccess(response, file, fileList) {
      if (response.code == 200) {
        this.form.accessoryList = '123'
        this.upload.form.accessoryList = '123'
        this.accessoryList.push(response.imgUrl)
      }
    },
    // 查看订单商品
    handleLook(row){
      this.orderProductTable = []
      this.fileList = []
      this.orderCode = row.orderCode
      getPriceComparisonOrder(row.orderCode).then(response => {
        this.openLook = true
        let data = response.data
        this.orderProductTable = data.products
        let accessoryList = data.accessoryList
        if (accessoryList && accessoryList.length > 0) {
          accessoryList.forEach(item => {
            let urls = item.split("/")
            this.fileList.push({name: urls[urls.length - 1], url: this.prefix + item})
          })
        }
      })
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs["formImport"].validate(valid => {
        if (valid) {
          this.$refs.upload.submit();
        }
      })
    },
    cancelImport() {
      this.upload.open = false
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "出价单导入";
      this.upload.form.manufacturerId = null
      this.upload.form.manufacturerName = null
      this.upload.form.accessoryList = null
      this.upload.form.jhValid = null
      this.upload.form.isBj = 'Y'
      this.accessoryList = []
      this.fileList = []
      this.upload.open = true;
    },
    /** 比价按钮操作 */
    handleContrast() {
      this.reset()
      getPriceComparisonInquire().then(response => {
        this.inquireOrderContrastOptions = response.data
        this.title = "比价单比价";
        this.openContrast = true
      })
    },
    /** 比价提交按钮 */
    submitFormContrast() {
      this.$refs["formContrast"].validate(valid => {
        if (valid) {
          this.btnLoading = true
          getContrastInquireOrder(this.formContrast).then(response => {
            if (response.code == 200) {
              this.contrastProductTable = response.data
              this.contrastProductTable.forEach((item, index) => {
                item.showFlag = false
                let allPrice =0
                item.products.forEach(product => {
                  product.tableIndex = index
                  allPrice += parseFloat(product.oldAllPrice)
                })
                item.allPrice = parseFloat(allPrice).toFixed(2)
              })
              this.openContrast = false;
              this.openContrastDetail = true;
            } else {
              this.$modal.msgError(response.msg);
            }
          }).finally(f => {
            this.btnLoading = false
          });
        }
      });
    },
    /** 比价详情提交按钮 */
    submitFormContrastDetail() {
      let contrastInfo = this.$refs.comparisonProduct.getSelectedProductList()
      if (contrastInfo.products && contrastInfo.products.length > 0) {
        contrastInfo.inquireCode = this.formContrast.inquireCode
        this.btnLoading = true
        contrastPriceComparisonOrder(contrastInfo).then((response) => {
          if (response.code == 200) {
            this.$modal.msgSuccess("比价单提交成功，等待审核")
            this.openContrastDetail = false;
            this.getList()
          } else {
            this.$modal.msgError(response.msg);
          }
        }).finally(e => {
          this.btnLoading = false
        })
      }
    },
    // 文件点击事件
    handlePreview(file){
      window.open(file.url,'_blank');
    },
  }
};
</script>
<style scoped>
/deep/ .el-select{
  width: 100%;
}
/deep/ .el-upload-dragger{
  width: 100%;
}
/deep/ .el-upload{
  width: 100%;
}
/deep/ .bjDetail .el-dialog__body{
  height: calc(100% - 119.6px);
  overflow-y: auto;
}
</style>
